package com.bawei.lib_common.websocket

import android.util.Log
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.google.gson.reflect.TypeToken
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.WebSocket
import okhttp3.WebSocketListener
import org.json.JSONObject

class LiveWebSocketManager(
    private val roomId: String,
    private val userId: Int,
    private val onRedPacket: (RedPacketMsg) -> Unit
) {
    private var webSocket: WebSocket? = null

    fun connect() {
        val request = Request.Builder()//2355
            .url("ws://10.161.9.80:7015/liveRoom/websocket/$roomId/$userId") // 替换为你的ws地址
            .build()
        val client = OkHttpClient()
        webSocket = client.newWebSocket(request, object : WebSocketListener() {
            override fun onMessage(webSocket: WebSocket, text: String) {
                val json=JSONObject(text)
                val type=json.optInt("type")
                if (type==5){
                    val data=json.optJSONObject("data")
                    val username=data?.optString("username")
                    if (!username.isNullOrEmpty()){

                    }

                }

                val msg = parseRedPacketMsg(text)
                if (msg != null) onRedPacket(msg)
                Log.w("WebSocket_RAW", text) // 强制打印所有原始数据
            }

            override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
                // 处理断线重连等
                Log.e("WebSocket", "连接失败: ${t.message}")
            }

            override fun onOpen(webSocket: WebSocket, response: Response) {
                Log.d("WebSocket", "连接已建立，房间号:$roomId")
                Log.d("WebSocket", webSocket.request().url.toString())
            }

        })
    }

    fun sendRedPacket(count: Int, diamond: Int, roomId: String, userId: Int) {
        val json = JSONObject().apply {
            put("type", 1) // 明确消息类型
            put("count", count)
            put("diamond", diamond)
            put("money", count * diamond) // 总金额
            put("roomId", roomId)
            put("time", System.currentTimeMillis())
            put("userId", userId)
        }
        Log.d("WebSocket", "主播端发送红包: $json")
        webSocket?.send(json.toString())
        Log.d("WebSocket", webSocket!!.request().url.toString())
    }

    fun close() {
        webSocket?.close(1000, "bye")
    }//haoka


    // 修改后的消息解析方法
    private fun parseRedPacketMsg(text: String): RedPacketMsg? {
        return try {
            val json = Gson().fromJson(text, JsonObject::class.java)
            // 只处理红包类型消息（假设type=1是红包）
            if (json.has("type") && json.get("type").asInt == 1) {
                Gson().fromJson(text, RedPacketMsg::class.java)
            } else {
                null
            }
        } catch (e: Exception) {
            null
        }
    }
}

data class RedPacketMsg(
    val count: Int,
    val diamond: Int,
    val money: Int,
    val roomId: String,
    val time: Int,
    val userId: Int
)
//class LiveWebSocketManager(
//    private val roomId: String,
//    private val userId: Int,
//    private val onRedPacket: (SessionEvent<RedPacketResult>) -> Unit
//) {
//    // 协议常量（与后台完全一致）
//    companion object {
//        const val TYPE_CONNECT = 0
//        const val TYPE_RED_PACKET = 1
//        const val TYPE_RED_PACKET_RESULT = 3
//        // 其他事件类型...
//    }
//
//    private var webSocket: WebSocket? = null
//    private val client = OkHttpClient()
//
//    fun connect() {
//        val request = Request.Builder()
//            .url("ws://10.161.9.80:7015/liveRoom/websocket/$roomId/$userId")
//            .build()
//
//        webSocket = client.newWebSocket(request, object : WebSocketListener() {
//            override fun onOpen(webSocket: WebSocket, response: Response) {
//                Log.d("WebSocket", "连接建立: ${webSocket.request().url}")
//            }
//
//            override fun onMessage(webSocket: WebSocket, text: String) {
//                Log.d("WebSocket", "收到原始消息: $text")
//                parseMessage(text)?.let { event ->
//                    when (event.type) {
//                        TYPE_RED_PACKET_RESULT -> onRedPacket(event)
//                        // 处理其他事件...
//                    }
//                }
//            }
//
//            override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
//                Log.e("WebSocket", "连接失败", t)
//                // 实现重连逻辑...
//            }
//        })
//    }
//
//    fun sendRedPacket(count: Int, diamond: Int) {
//        val event = SessionEvent(
//            type = TYPE_RED_PACKET,
//            data = RedPacketData(
//                count = count,
//                diamond = diamond,
//                roomId = roomId,
//                userId = userId
//            )
//        )
//        sendEvent(event)
//    }
//
//    private fun sendEvent(event: SessionEvent<*>) {
//        try {
//            val json = Gson().toJson(event)
//            Log.d("WebSocket", "发送事件: $json")
//            webSocket?.send(json) ?: throw IllegalStateException("WebSocket未连接")
//        } catch (e: Exception) {
//            Log.e("WebSocket", "发送失败", e)
//        }
//    }
//
//    private fun parseMessage(text: String): SessionEvent<RedPacketResult>? {
//        return try {
//            val typeToken = object : TypeToken<SessionEvent<JsonObject>>() {}.type
//            val rawEvent = Gson().fromJson<SessionEvent<JsonObject>>(text, typeToken)
//
//            when (rawEvent.type) {
//                TYPE_RED_PACKET_RESULT -> {
//                    val result = Gson().fromJson(rawEvent.data, RedPacketResult::class.java)
//                    SessionEvent(rawEvent.type, result)
//                }
//                else -> null
//            }
//        } catch (e: Exception) {
//            Log.e("WebSocket", "解析消息失败: $text", e)
//            null
//        }
//    }
//
//    fun close() {
//        webSocket?.close(1000, "正常关闭")
//        client.dispatcher.executorService.shutdown()
//    }
//}
//
//// 协议数据结构
//data class SessionEvent<T>(
//    val type: Int,
//    val data: T
//)
//
//// 发送红包数据结构（TYPE=1）
//data class RedPacketData(
//    val count: Int,
//    val diamond: Int,
//    val roomId: String,
//    val userId: Int,
//    val money: Int = count * diamond
//)
//
//// 接收红包结果（TYPE=3）
//data class RedPacketResult(
//    val success: Boolean,
//    val message: String?,
//    val remaining: Int
//)
